package com.grape.transaction.rabbitmq.service;

import com.alibaba.fastjson.JSONObject;
import com.grape.transaction.rabbitmq.constrant.CommConstrant;
import com.grape.transaction.rabbitmq.entity.OrderEntity;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 描述:OrderService   订单服务类
 * @author: myx
 * @date: 2019/6/10
 * Copyright © 2019-grape. All rights reserved.
 */
@Service
public class OrderService implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public String addOrder(int isFlag){
        String orderId = UUID.randomUUID().toString();
        try {
            OrderEntity orderEntity =new OrderEntity();
            orderEntity.setOrderMoney("10000");
            orderEntity.setOrderName("订单");
            orderEntity.setStatus(1);
            orderEntity.setOrderId(orderId);
            //入数据库
            int orderResult = 1;
            if (orderResult > 0) {
                //添加全局map
                CommConstrant.commMap.add(orderId);
            }else{
                return orderId+"===下单失败!";
            }
            //伪代码模拟异常
            if(isFlag%2==0){
                int i=1/0;
            }
            //使用消息中间件将参数存在派单队列中
            send(orderId);
            //消息发送成功后模拟异常
            try {
                if(isFlag%4==3){
                    int i=1/0;
                }
            }catch (Exception e){
                //e.printStackTrace();
                System.out.println(orderId+"===处理异常回滚");
                //回滚操作
                CommConstrant.commMap.remove(orderId);
            }finally {
                System.out.println(orderId+"===下单成功");
                return orderId+"===下单成功";
            }
        }catch (Exception e){
            System.out.println(orderId+"===下单失败");
            return orderId+"===下单失败!";
        }
    }


    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String orderId = correlationData.getId();
        //System.out.println("消息id:" + correlationData.getId());
        if (ack) {
            System.out.println(orderId+"===消息发送确认成功");
        } else {
            send(orderId);
            System.out.println(orderId+"===消息发送确认失败:" + cause);
        }
    }

    /**
     * 发送消息
     * @param orderId
     */
    private void send(String orderId) {
        JSONObject jsonObect = new JSONObject();
        jsonObect.put("orderId", orderId);
        String msg = jsonObect.toJSONString();
        //System.out.println("msg:" + msg);
        // 封装消息
        Message message = MessageBuilder.withBody(msg.getBytes()).setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setContentEncoding("utf-8").setMessageId(orderId).build();
        // 构建回调返回的数据
        CorrelationData correlationData = new CorrelationData(orderId);
        // 发送消息
        this.rabbitTemplate.setMandatory(true);
        this.rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.convertAndSend("order_exchange_name", "orderRoutingKey", message, correlationData);
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.out.println("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}"+exchange+routingKey+replyCode+replyText+message);
    }
}
